// this need to get call from the beginning
// so make this available in different places
const fsx = require('fs-extra')
const { join } = require('path')
const contractApi = require('jsonql-contract')
const {
  DEFAULT_CONTRACT_FILE_NAME,
  PUBLIC_CONTRACT_FILE_NAME
} = require('jsonql-constants')

const debug = require('debug')('jsonql-koa::contract-generator')
/**
 * @param {string} contractDir where the contract is
 * @param {boolean} pub system of public
 * @return {mixed} false on not found
 */
const readContract = function(contractDir, pub) {
  const file = join(contractDir, pub ?  PUBLIC_CONTRACT_FILE_NAME : DEFAULT_CONTRACT_FILE_NAME)
  if (fsx.existsSync(file)) {
    debug('Serving up the existing one from ', file)
    return fsx.readJsonSync(file)
  }
  return false;
}

/**
 * contract create handler
 * @param {object} opts options
 * @param {boolean} pub where to serve this
 * @param {boolean} start is this the first call
 * @return {object} promise to resolve contract json
 */
const contractGenerator = function(opts, pub = false, start = false) {
  return new Promise((resolver, rejecter) => {
    if (opts.buildContractOnStart === false && start === false) {
      const contract = readContract(opts.contractDir, pub)
      if (contract !== false) {
        return resolver(contract)
      }
    }
    contractApi(Object.assign({}, opts, { public: pub }))
      .then(resolver)
      .catch(rejecter)
  })
}

// export
module.exports = {
  contractGenerator,
  readContract
}
